package done;

import java.awt.Dimension;
import java.util.LinkedList;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;


public class PresenceViewer extends SwingWorker<Boolean, Boolean> implements
		ScaleWriter {

	private JPanel threadPanel;
	private Icon icon;
	private double old=0;
	private double nextData = 0;
	private String nextTime = new String();
	private LinkedList<Information> list = new LinkedList<Information>();

	public PresenceViewer() {
		list = new LinkedList<Information>();
		icon=new ImageIcon("lib/Active.jpg");
		
	}

	@Override
	protected Boolean doInBackground() throws Exception {
		Information i;	
		while ((i = list.poll()) != null ) {
			nextData = i.getData();
			nextTime = i.getTime();
			if(old!=nextData){
				System.out.println("new data "+nextData);
				old=nextData;
				threadPanel.removeAll();
			for(int j=0;j<(int)nextData;j++){
			JLabel label = new JLabel(icon);
			label.setToolTipText((int)nextData + " people in room \n starting from " + nextTime );
			label.setBounds(j*25+5, 5, 25, 25);
			label.setOpaque(true);			
			threadPanel.add(label);
			threadPanel.setPreferredSize(new Dimension((int)nextData*30, size));
			threadPanel.setSize(new Dimension((int)nextData*30, size));
			threadPanel.repaint();
			}
		
			}
		}
		if(i==null && hasFinished==false){		
			while(list.size()<1 && hasFinished==false)
				{
					Thread.sleep(10);
				}
				doInBackground();
			}else 
			{
				System.out.println("done2");
				return true;
			}		
		System.out.println("done1");
		return true;
	}

	@Override
	public void writeNext(Information i) {
			list.add(i);
	}

	@Override
	public void setPanel(JPanel panel) {
		threadPanel = panel;

	}

	private boolean hasFinished = false;

	@Override
	public void finished() {
		hasFinished = true;
	}
	
	public void runWorker()
	{
		this.execute();
	}

}